package com.cskaoyan.service;


import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.domain.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketAdminMapper adminMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketCollectMapper collectMapper;
    @Autowired
    MarketFootprintMapper footprintMapper;
    @Override
    public Integer getAllGoodsCount() {
        return goodsMapper.selectGoods();
    }

    @Override
    @Transactional
    public Map<String, Object> getGoodsDetails(Integer id) {
        Map<String, Object> map=new HashMap<>();
        //attribute的获取
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> goodsAttributes = attributeMapper.selectByExampleSelective(attributeExample);
        map.put("attribute",goodsAttributes);
        //brand的获取
        MarketGoods goods = marketGoodsMapper.selectByPrimaryKey(id);
        Integer brandId = goods.getBrandId();
        MarketBrand brand = brandMapper.selectByPrimaryKey(brandId);
        map.put("brand",brand);
        //comment的获取
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        List<MarketComment> comments = commentMapper.selectByExampleSelective(commentExample);
        GoodsCommentsVo comment = new GoodsCommentsVo();
        if (comments.size() == 0) {
            comment.setCount(0);
        }
        else {
            List<CommentData> data=new ArrayList<>();
            Integer count=0;
            for (MarketComment goodComment : comments) {
                //详情页最多展示两条评论
                if (count < 2) {
                    CommentData commentData = new CommentData();
                    commentData.setAddTime(goodComment.getAddTime());
                    commentData.setAdminContent(goodComment.getAdminContent());
                    commentData.setContent(goodComment.getContent());
                    commentData.setId(goodComment.getId());
                    String[] picUrls = goodComment.getPicUrls();
                    List<String> picList=new ArrayList<>();
                    for (String picUrl : picUrls) {
                        picList.add(picUrl);
                    }
                    commentData.setPicList(picList);
                    //找admin表的username和avatar
                    MarketAdmin admin = adminMapper.selectByPrimaryKey(goodComment.getUserId());
                    commentData.setNickname(admin.getUsername());
                    commentData.setAvatar(admin.getAvatar());
                    data.add(commentData);
                }
                count++;
            }
            comment.setCount(count);
            comment.setData(data);
        }
        map.put("comment",comment);
        //groupon的获取,数据库中groupon表为空，暂时都返回空数组
        List<MarketGroupon> grouponList=new ArrayList<>();
        map.put("groupon",grouponList);
        //info的获取,就是把goods表中的所有数据封装
        map.put("info",goods);
        //issue的获取，把issue表中所有数据封装
        MarketIssueExample issueExample = new MarketIssueExample();
        List<MarketIssue> issues = issueMapper.selectByExample(issueExample);
        map.put("issue",issues);
        //productList的获取,根据goodsid找到所有products
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> productList = productMapper.selectByExample(productExample);
        map.put("productList",productList);
        //share的获取，查system表的key和value
        MarketSystemExample systemExample = new MarketSystemExample();
        String share = systemMapper.selectKeyNameAndKeyValue("market_wx_share");
        map.put("share",share);
        //shareImage获取
        if ("true".equals(map.get("share"))) {
            String shareUrl = goods.getShareUrl();
            map.put("shareImage", shareUrl);
        } else {
            map.put("shareImage","");
        }
        //specificationList获取,有name和valuelist属性,name就是specification字段，按照name进行分类
        SpecificationVo specificationVo = new SpecificationVo();
        //Map<String,Object> specificationMap=new HashMap<>();
        List<SpecificationVo> specificationList=new ArrayList<>();
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExampleSelective(specificationExample);
        for (MarketGoodsSpecification specification : specifications) {
            String name = specification.getSpecification();
            for (SpecificationVo sv : specificationList) {
                if (name.equals(sv.getName())) {
                    List<MarketGoodsSpecification> valueList = sv.getValueList();
                    valueList.add(specification);
                    continue;
                }
            }
            List<MarketGoodsSpecification> valueList=new ArrayList<>();
            valueList.add(specification);
            SpecificationVo newSpecificationVo = new SpecificationVo();
            newSpecificationVo.setName(name);
            newSpecificationVo.setValueList(valueList);
            specificationList.add(newSpecificationVo);
        }
        map.put("specificationList",specificationList);
        //获取收藏数userhascollect
        MarketCollectExample collectExample = new MarketCollectExample();
        collectExample.createCriteria().andValueIdEqualTo(id);
        List<MarketCollect> collectList = collectMapper.selectByExampleSelective(collectExample);
        Integer userHasCollect=collectList.size();
        map.put("userHasCollect",userHasCollect);
        //浏览记录添加
        MarketFootprint footprint = new MarketFootprint();
        footprint.setDeleted(false);
        Subject subject = SecurityUtils.getSubject();
        Integer userId=0;
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            userId = principal.getId();
        }
        footprint.setUserId(userId);
        footprint.setGoodsId(goods.getId());
        footprint.setAddTime(LocalDateTime.now());
        footprint.setUpdateTime(LocalDateTime.now());
        footprintMapper.insertSelective(footprint);
        return map;
    }

    @Override
    public BaseRespVo selectRelatedById(Integer id) {
        MarketGoods goods = marketGoodsMapper.selectByPrimaryKey(id);
        if (goods == null) {
            return BaseRespVo.badArgument();
        }
        Integer categoryId = goods.getCategoryId();
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId);
        PageHelper.startPage(1,6);
        List<MarketGoods> goodsList = marketGoodsMapper.selectByExampleSelective(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(goodsList);
        CommonData data = CommonData.data(pageInfo);
        return BaseRespVo.ok(data);
    }
    @Override
    public List<MarketGoods> getGoodsByCategoryId(int cid) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(cid);
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        return marketGoods;
    }

    @Override
    public List<MarketGoodsProduct> getProductById(Integer id) {
        MarketGoodsProductExample example = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(example);
        return marketGoodsProducts;
    }

    @Override
    public List<MarketGoods> getGoodsByBrandId(Integer brandId) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andBrandIdEqualTo(brandId);
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        return marketGoods;
    }

    @Override
    public List<CollectionGoodsVo> selectGoodCollectionListById(int userId) {
        MarketCollectExample collectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = collectExample.createCriteria();
        criteria.andIdEqualTo(userId);
        List<MarketCollect> collectList = collectMapper.selectByExample(collectExample);

        List<CollectionGoodsVo> collectionGoodsVoList = new ArrayList<>();
        for (MarketCollect marketCollect : collectList) {
            MarketGoods good = marketGoodsMapper.selectByPrimaryKey(marketCollect.getValueId());
            CollectionGoodsVo collectionGood = new CollectionGoodsVo();
            collectionGood.setBrief(good.getBrief());
            collectionGood.setName(good.getName());
            collectionGood.setPicUrl(good.getPicUrl());
            collectionGood.setRetailPrice(good.getRetailPrice());
            collectionGood.setType((byte) 0);
            collectionGood.setValueId(good.getId());
            collectionGoodsVoList.add(collectionGood);
        }
        return collectionGoodsVoList;
    }
    @Override
    public List<MarketGoods> getGoodsLike(String keyword,String sort,String order) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andNameLike("%"+keyword+"%");
        marketGoodsExample.setOrderByClause(sort+" "+order);
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        return marketGoods;
    }
}